var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');

var app = express();

//@ykit-->begin
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/public'));
// var redis = require('redis'),
    // db = redis.createClient();
	
// db.on('ready',function(err){
    // console.log('ready');
// });

global.db = require('./db');	//包含文件
//<--end

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', index);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

//@ykit-->begin

//在线用户
var onlineUsers = {};
//当前在线人数
var onlineCount = 0;

var guid = 1;
function getnewguid(){
	var nguid = 0xffffffff&guid;
	guid++;
	return nguid; 
}

function newuser(){
	return {
		info:{},
		roles:[],
		equips:{},
		cards:{},
	}
}

io.on('connection', function(socket){
	socket.name = getnewguid();
	console.log('a user connected:'+socket.name);
	var u = newuser();
	u.info.name = socket.name;
	onlineUsers[socket.name] = u;
	
	//监听新用户加入
	socket.on('login', function(obj){
		console.log('login msg');
		// if(obj.name != obj.pass){
			// socket.emit('login',{success:false,info:'password invalid!'});
			// return;
		// }
		global.db.get(obj.name,function(error, res) {
			if(error) {
                console.log(error);
				socket.emit('login',{success:false,info:'password invalid!'});
				return;
            } else {
                //console.log(res);
				if(obj.pass != res)
				{
					console.log('login err');
					socket.emit('login',{success:false,info:'password invalid!'});
					return;
				}
            }
		});
		
	    global.db.set(obj.name, obj.pass,'30',function(error, res) {
			if(error) {
                console.log(error);
				socket.emit('login',{success:false,info:'password invalid!'});
				return;
            } else {
                console.log(res);
            }
		});
		
		var u = onlineUsers[socket.name];
		// 删除临时数据
		delete onlineUsers[socket.name];
		//将新加入用户的唯一标识当作socket的名称，后面退出的时候会用到
		socket.name = obj.name;
		u.info.name = obj.name;
		onlineUsers[socket.name] = u;
		
		//检查在线列表，如果不在里面就加入
		if(!onlineUsers.hasOwnProperty(obj.name)) {
			onlineUsers[obj.name] = obj.name;
			//在线人数+1
			onlineCount++;
		}

		socket.emit('login',{success:true,info:u.info,roles:u.roles});
		
	});

	// 创建角色
	socket.on('newrole',function(obj){
		var u = onlineUsers[socket.name];
		var r = {};
		r.hp = 10;
		r.mp = 1;
		r.atk = 1;
		r.roleid = obj.id;
		r.id = getnewguid();
		u.roles.push(r);

		socket.emit('newrole',{success:true,role:r}); 
	});
	
	//监听用户退出
	socket.on('disconnect', function(){
		console.log('a user disconnected:'+socket.name);
		//将退出的用户从在线列表中删除
		if(onlineUsers.hasOwnProperty(socket.name)) {			
			//删除
			delete onlineUsers[socket.name];
			//在线人数-1
			onlineCount--;
		}
	});  
});

http.listen(3000, function(){
	console.log('listening on *:3000');
});

//-->end